import glob
import time

import cv2
import numpy as np
# termination criteria
from scipy.io import savemat

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((9 * 6, 3), np.float32)
objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)

# Arrays to store object points and image points from all the images.
objpoints = []  # 3d point in real world space
imgpoints = []  # 2d points in image plane.

images = glob.glob("./output/*.png")
# 刚刚采集的照片的位置
img = cv2.imread(images[0])
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
for fname in images:
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Find the chess board corners
    ret, corners = cv2.findChessboardCorners(gray, (9, 6), None)

    # If found, add object points, image points (after refining them)

    if ret == True:
        objpoints.append(objp)

        corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
        imgpoints.append(corners2)

        # Draw and display the corners
        img = cv2.drawChessboardCorners(img, (9, 6), corners2, ret)
        cv2.imshow('img', img)
        cv2.waitKey(10)

cv2.destroyAllWindows()
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)

w, h = 640, 480
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1,
                                                  (w, h))
savemat("mtx.mat", {"mtx": mtx, "new_mtx": newcameramtx, "dist": dist, 'roi': roi})
cap = cv2.VideoCapture(0)  # 创建一个 VideoCapture 对象
# cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
total_time = []
while (cap.isOpened()):  # 循环读取每一帧0
    ret_flag, img = cap.read()
    # undistort
    tic = time.time()
    dst = cv2.undistort(img, mtx, dist, None, newcameramtx)
    print(f'!!!!!!!!!!!!{roi}')
    x, y, w, h = roi
    dst = dst[y:y + h, x:x + w]
    # dst = cv2.resize(dst[y:y + h, x:x + w], (320, 240))
    # toc = time.time()
    # total_time.append(toc - tic)
    cv2.imshow('dst', dst)
    # crop the image

    k = cv2.waitKey(1)
    if k == ord("p"):
        print(dst.shape)
        print(np.mean(total_time))
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
